package sg.edu.nus.iss;

import java.io.*;
import java.util.*;

/**
 * 
 * @author Xu Guoneng
 *
 */
public class InputParser {

	public static HashMap<String, String> parseConfigFile(String filePath){
		try{
			  HashMap<String, String> map = new HashMap<String, String>();

			  BufferedReader input =  new BufferedReader(new FileReader(filePath));
			  
		      try {
		    	  String line = null;
		    	   while((line = input.readLine()) != null){
		    		   StringTokenizer st = new StringTokenizer(line, " \t=");
		    		   map.put(st.nextToken(), st.nextToken());
		    	   }
		      }
		      finally {
		        input.close();
		      }

		      return map;
		}
		catch(Exception ex){
			throw new RuntimeException(ex);
		}
	}
	
	public static Package[] parseDataFile(String filePath,  int numOfRecords){
		try{
			  Package[] packages = new Package[numOfRecords];
			  BufferedReader input =  new BufferedReader(new FileReader(filePath));
			  
		      try {
			    	  for(int i=0; i < numOfRecords;){
			    		  String line = input.readLine();
			    		  Package p = createPackage(line);
			    		  if(p != null){
			    			  packages[i] = p;
			    			  i++;
			    		  }
			    	  }
		      }
		      finally {
		        input.close();
		      }

		      return packages;
		}
		catch(Exception ex){
			throw new RuntimeException(ex);
		}
		
	}
	
	private static Package createPackage(String line){
		line = line.trim();
		StringTokenizer st = new StringTokenizer(line, " \t");
		
		String t1 = st.nextToken();
		if(t1.charAt(0) != '#'){
			Integer id = Integer.parseInt(t1);
			Double weight = Double.parseDouble(st.nextToken());
			Integer categoryCd = Integer.parseInt(st.nextToken());
			return new Package(id, weight, categoryCd);
		}

		return null;
	}
}
